import type { TSafeTopArea } from '@/types/common'

/**
 * @description 获取uniapp api的返回值
 * @param api uniapp对应的api
 * @param callback 可选 对应callback
 * @returns
 */
export const getUniApiSyncRes = (api: string, callback?: () => void): [boolean, any] => {
  try {
    let data = null
    const canUse = uni.canIUse(api)
    if (canUse) {
      data = uni[api]()
    }
    return [!canUse, data]
  } catch (error) {
    return [error, null]
  }
}

/** 获取顶部安全边距 */
export const getSafeTopArea = (): TSafeTopArea => {
  const [statusErr, statusData] = getUniApiSyncRes('getSystemInfoSync')
  const [menuErr, menuData] = getUniApiSyncRes('getMenuButtonBoundingClientRect')
  const safeObj = {
    statusBarHeight: 0,
    menuBtnHeight: 0,
  }

  if (!statusErr) {
    safeObj.statusBarHeight = statusData?.statusBarHeight
  }
  if (!menuErr) {
    safeObj.menuBtnHeight = (menuData.top - safeObj.statusBarHeight) * 2 + menuData.height
  }

  return safeObj
}
